// const db = require('../db/mysql')

// 导入cb模块代替db模块发送数据库请求解决回调地狱问题
const cb = require('../promise/cb')

// 导入数据整理模块
const _ = require('lodash')

exports.menu = async(req, res) => {
    const sql = 'SELECT * FROM sp_permission_api LEFT JOIN sp_permission ON sp_permission_api.ps_id = sp_permission.ps_id'

    // db.query(sql, (err, results) => {
    //     if (err) return res.ResInfo(err)
    //     var firstMenu = {}
    //     for (id in results) {
    //         item = results[id]
    //         if (item.ps_level == 0) {
    //             firstMenu[item.ps_id] = {
    //                 "id": item.ps_id,
    //                 "authName": item.ps_name,
    //                 "children": []
    //             }
    //         }
    //     }

    //     for (id in results) {
    //         item = results[id]
    //         if (item.ps_level == 1) {
    //             fItem = firstMenu[item.ps_pid]
    //             if (fItem) {
    //                 fItem.children.push({
    //                     "id": item.ps_id,
    //                     "authName": item.ps_name,
    //                     "path": item.ps_api_path
    //                 })
    //             }
    //         }
    //     }
    //     res.ResInfo('数据获取成功', 200, firstMenu)
    // })

    const results = await cb(sql).catch((err) => {
        res.ResInfo(err)
    })

    // console.log(results)

    var rootMenu = {}

    for (id in results) {
        let item = results[id]
        if (item.ps_level == 0) {
            rootMenu[item.ps_id] = {
                "authName": item.ps_name,
                "id": item.ps_id,
                children: [],
                "order": item.ps_api_order
            }
        }
    }

    for (id in results) {
        let item = results[id]
        if (item.ps_level == 1) {
            let fItem = rootMenu[item.ps_pid]
            if (fItem) {
                fItem.children.push({
                    "authName": item.ps_name,
                    "id": item.ps_id,
                    "path": item.ps_api_path,
                    children: [],
                    "order": item.ps_api_order
                })
            }
        }
    }

    // 通过order进行排序
    result = _.values(rootMenu);
    result = _.sortBy(result, "order");
    for (idx in result) {
        subresult = result[idx];
        subresult.children = _.sortBy(subresult.children, "order");
    }
    // console.log(result)
    res.ResInfo("数据获取成功", 200, result)
}